<!--
@Description:局部滚动
@Author:zqy
@Date:2023-04-20 10:07:22
@Last Modified by:zqy
@Last Modified time:2023-04-20 10:07:22
 -->
<template>
  <div
    ref="box"
    :class="className"
    :style="styleObj"
    @touchstart="stopPropagation"
    @touchend="stopPropagation"
    @touchmove="stopPropagation"
    @scroll.stop="scrollHandle"
  >
    <slot></slot>
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, reactive, ref, toRefs } from 'vue'
  export default defineComponent({
    name: 'Scroll',
    props: {
      vertical: {
        type: Boolean,
        default: false
      },
      horizontal: {
        type: Boolean,
        default: false
      },
      height: {
        type: String,
        default: 'auto'
      },
      width: {
        type: String,
        default: '100%'
      },
      hiddenBar: {
        type: Boolean,
        default: true
      },
      stop: {
        type: Boolean,
        default: false
      }
    },
    setup(props, ctx) {
      const box = ref()
      const datas = reactive({
        scrollTop: 0,
        scrollLeft: 0
      })
      const className = computed(() => {
        const classList = ['scroll']
        if (props.vertical) {
          classList.push('vertical')
        }
        if (props.horizontal) {
          classList.push('horizontal')
        }
        if (props.hiddenBar) {
          classList.push('scroll-bar-hidden')
        }
        return classList
      })
      const styleObj = computed(() => {
        const style = {
          width: 'auto',
          height: 'auto'
        }
        props.width ? (style.width = props.width) : ''
        props.height ? (style.height = props.height) : ''
        return style
      })
      const scrollBox = box.value
      const scrollHandle = (e: any) => {
        ctx.emit(
          'on-scroll',
          e.target.scrollTop,
          e.target.scrollLeft,
          e.target.scrollTop - datas.scrollTop,
          e.target.scrollLeft - datas.scrollLeft
        )
        datas.scrollTop = e.target.scrollTop
        datas.scrollLeft = e.target.scrollLeft
      }
      const stopPropagation = (e: any) => {
        if (props.stop) {
          e.stopPropagation()
        }
      }
      const scrollTo = (x: any, y: any) => {
        scrollBox.scrollLeft = x
        scrollBox.scrollTop = y
      }
      return {
        ...toRefs(datas),
        className,
        styleObj,
        scrollBox,
        scrollHandle,
        stopPropagation,
        scrollTo
      }
    }
  })
</script>
<style lang="less">
  .scroll {
    width: 100%;
  }
  .scroll-bar-hidden {
    &::-webkit-scrollbar {
      display: none;
      width: 0;
      height: 0;
    }
  }
  .horizontal {
    overflow-x: auto;
  }
  .vertical {
    overflow-y: auto;
  }
</style>
